package com.jk.customer.service.impl;

import com.jk.customer.dao.TreeDao;
import com.jk.customer.entity.TreeEntity;
import com.jk.customer.entity.UserEntity;
import com.jk.customer.service.TreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TreeServiceImpl implements TreeService {
    @Autowired
    private TreeDao treeDao;

    /**
     * 登录
     * @param user
     * @param session
     * @return
     */
    @Override
    public Map<String,Object> login(UserEntity user, HttpSession session) {
        Map<String,Object> map = new HashMap<>();

        UserEntity user2 = treeDao.getUserByAccount(user.getUserAccout());
        if (user2==null){
            map.put("code",201);
        }else {
            if (!user.getUserPassword().equals(user2.getUserPassword())){
                map.put("code",201);
            }else{
                map.put("code",200);
                session.setAttribute("user",user2);
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> registerUser(UserEntity user) {
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = treeDao.findUserByAccount(user.getUserAccout());
        if(userEntity == null){
            treeDao.addUser(user);
            map.put("message","注册成功");
        }else {
            map.put("message","该用户已存在");
        }
        return map;
    }

    @Override
    public Map<String, Object> addUserInfo(UserEntity user) {

        Map<String, Object> map = new HashMap<>();

        try {
            treeDao.addUserInfo(user);
            map.put("message","保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message","保存失败");
        }
        return map;
    }

    /**
     * 树列表查询
     * @param pid
     * @param session
     * @return
     */
    @Override
    public List<TreeEntity> getTree(Integer pid, HttpSession session) {
        UserEntity user = (UserEntity) session.getAttribute("user");
        Integer userType = user.getUserType();
        if (userType == 2){
            List<TreeEntity> list = treeDao.getSellerTree(pid);
            for (TreeEntity tree : list) {
                tree.setNodes(getTree(tree.getId(), session));
            }
            return list;
        }else{
            List<TreeEntity> list = treeDao.getBuyerTree(pid);
            for (TreeEntity tree : list) {
                tree.setNodes(getTree(tree.getId(), session));
            }
            return list;
        }

    }



}
